package com.zerdoor.service.impl;

import com.zerdoor.dao.ICommonPayDao;
import com.zerdoor.service.ICommonPayService;
import com.zerdoor.service.RaceOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhongjieyu on 2014/12/23.
 */
@Service
public class CommonPayServiceImpl implements ICommonPayService {

    @Autowired
    private ICommonPayDao commonPayDao;
    @Autowired
    private RaceOrderService raceOrderService;

    @Override
    public float findUserWalletEnough(Integer userId) throws Exception {



        return commonPayDao.findUserWalletEnough(userId);
    }

    @Override
    public boolean updateDeductUserWalletByUserId(float sumPrice, Integer userId, Integer type) throws Exception {

        //参数
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("sumPrice",sumPrice);
        param.put("user_id",userId);

        // 钱包记录map
        Map<String,Object> walletMap = new HashMap<String, Object>();

        //封装日志信息
        walletMap.put("money",sumPrice );
        walletMap.put("type", type );
        walletMap.put("user_id", userId );

//      根据用户ID和订单总金额查询余额是否足够,账户是否冻结
        Map<String,String> userWalletMap = commonPayDao.findUserWalletByUserId(param);

        //如果等于空就表示账户余额不足或者账户被冻结
        if(userWalletMap == null){

            //失败状态
            walletMap.put("wallet_status", "131102");
            walletMap.put("remark", "支付失败！账户余额不足或账户被冻结！");
            //写入钱包使用记录
            commonPayDao.addUser_wallet(walletMap);

            return false;
        }


        //从用户钱包中扣除金额
        commonPayDao.updateDeductUserWalletByUserId(param);
        //成功状态
        walletMap.put("wallet_status", "131101");
        walletMap.put("remark", "支付成功！");

        //写入钱包使用记录
        commonPayDao.addUser_wallet(walletMap);


        return true;

    }

    @Override
    public boolean updateChargeUserWalletByUserId(float money,Integer userId,Integer type) throws Exception {

        //参数
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("money",money);
        param.put("user_id",userId);


        // 钱包记录map
        Map<String,Object> walletMap = new HashMap<String, Object>();

        //封装日志信息
        walletMap.put("money",money );
        walletMap.put("type", type );
        walletMap.put("user_id", userId );

        //收入，更新用户账户余额
        commonPayDao.updateChargeUserWalletByUserId(param);

        //成功状态
        walletMap.put("wallet_status", "131101");
        walletMap.put("remark", "收入成功！");
        //写入钱包使用记录
        commonPayDao.addUser_wallet(walletMap);

        return true;

    }

    @Override
    public boolean updateThawFreezeMoneyByUserId(float money, Integer userId, Integer type, boolean orderType, Integer orderId) throws Exception {

        //参数
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("money",money);
        param.put("user_id",userId);

        // 钱包记录map
        Map<String,Object> walletMap = new HashMap<String, Object>();

        //封装日志信息
        walletMap.put("money",money );
        walletMap.put("type", type );
        walletMap.put("user_id", userId );

        String orderTypeMsg = "竞赛活动订单";

        if(orderType){
            orderTypeMsg = "任务订单";
        }



        //更新冻结金额
        commonPayDao.updateThawFreezeMoneyByUserId(param);


        //成功状态
        walletMap.put("wallet_status", "131101");
        walletMap.put("remark", "解冻成功！订单ID：" + orderId +"，订单类型：" + orderTypeMsg);

        //写入钱包使用记录
        commonPayDao.addUser_wallet(walletMap);


        return true;
    }

    @Override
    public float findScaleValue(int configId) throws Exception {


        return commonPayDao.findScaleValue(configId);
    }

    @Override
    public boolean updateBlockedUserWalletByUserId(float sumPrice, Integer userId, Integer type, Integer orderId,boolean orderType,boolean isDeposit) throws Exception {
        //参数
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("sumPrice",sumPrice);
        param.put("user_id",userId);

        // 钱包记录map
        Map<String,Object> walletMap = new HashMap<String, Object>();

        //封装日志信息
        walletMap.put("money",sumPrice );
        walletMap.put("type", type );
        walletMap.put("user_id", userId );

        String orderTypeMsg = "竞赛活动订单";

        if(orderType){
            orderTypeMsg = "任务订单";
        }

//      根据用户ID和订单总金额查询余额是否足够,账户是否冻结
        Map<String,String> userWalletMap = commonPayDao.findUserWalletByUserId(param);

        //如果等于空就表示账户余额不足或者账户被冻结
        if(userWalletMap == null){

            //失败状态
            walletMap.put("wallet_status", "131102");
            walletMap.put("remark", "支付失败！账户余额不足或账户被冻结！订单ID：" + orderId +"，订单类型：" + orderTypeMsg);
            //写入钱包使用记录
            commonPayDao.addUser_wallet(walletMap);

            return false;
        }


        //更新冻结金额
        commonPayDao.updateFreezeUserWalletByUserId(param);

        //true 表示任务订单 false 表示竞赛活动订单
        if(orderType){

            //放入订单ID
            param.put("order_task_id",orderId);

            //放入状态
            param.put("status",0);
            if(!isDeposit){
                param.put("status",1);
            }

            //更新订单冻结金额字段等
            commonPayDao.updateOrderTaskBlockedInfo(param);
        }

        //成功状态
        walletMap.put("wallet_status", "131101");
        walletMap.put("remark", "冻结金额成功！订单ID：" + orderId +"，订单类型：" + orderTypeMsg);

        //写入钱包使用记录
        commonPayDao.addUser_wallet(walletMap);


        return true;

    }

	@Override
    public boolean isUserWalletEnough(float sumPrice, Integer userId) throws Exception {

        float wallet = commonPayDao.findUserWalletEnough(userId);

        if(wallet <= 0 ){

            return false;
        }

        if((wallet - sumPrice) < 0 ){

            return false;
        }

        return true;
    }

    @Override
    public boolean updateFreezeMoneyByUserId(float sumPrice, Integer userId, Integer type, Integer orderId ,boolean orderType) throws Exception {
        //参数
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("sumPrice",sumPrice);
        param.put("user_id",userId);

        // 钱包记录map
        Map<String,Object> walletMap = new HashMap<String, Object>();

        //封装日志信息
        walletMap.put("money",sumPrice );
        walletMap.put("type", type );
        walletMap.put("user_id", userId );

        String orderTypeMsg = "竞赛活动订单";

        if(orderType){
            orderTypeMsg = "任务订单";
        }

        //得到用户冻结金额
        float freezeMoney = commonPayDao.findFreezeMoneyByUserId(userId);

        if(freezeMoney - sumPrice < 0){

            //失败状态
            walletMap.put("wallet_status", "131102");
            walletMap.put("remark", "扣除冻结金额失败！账户冻结余额不足！订单ID：" + orderId +"，订单类型：" + orderTypeMsg);
            //写入钱包使用记录
            commonPayDao.addUser_wallet(walletMap);

            return false;
        }

        //扣除冻结金额和账户余额
        commonPayDao.updateFreezeMoneyByUserId(param);


        //成功状态
        walletMap.put("wallet_status", "131101");
        walletMap.put("remark", "扣除冻结金额成功！订单ID：" + orderId +"，订单类型：" + orderTypeMsg);

        //写入钱包使用记录
        commonPayDao.addUser_wallet(walletMap);

        return true;
    }

    @Override
    public void updateRaceMoney(List<Map<String, Object>> list,boolean isFee,boolean isPopur,int raceId,BigDecimal totalPrice,int userId,int orderRaceId) throws Exception {
        //获取艺术家获取奖金系数=手续费%*推广费%
        BigDecimal xishu = getXiShu(isFee, isPopur);
        //哈哈给艺术家发奖金
        updateArtistWallet(list, xishu, raceId, orderRaceId);
        //扣除委托方发布竞赛的资金，多余的返回，并写入日志。
        updateBaileWallet(totalPrice, userId, raceId);
    }

    @Override
    public void updateUserTradingNumByUserId(Integer userId) throws Exception {

    }


    /**
     * 扣除委托方发布竞赛的资金
     * @param totalPrice 订单总价
     * @param userId 发布竞赛用户
     * @param raceId 竞赛活动编号
     */
    private void updateBaileWallet(BigDecimal totalPrice,int userId,int raceId) throws Exception{
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("userId",userId);
        map.put("totalPrizeMoney",totalPrice);
        try{
            commonPayDao.updateBailseWallet(map);
        }catch (Exception e){
            throw new Exception("发布竞赛活动用户扣钱失败");
        }
        map.put("user_id",userId);
        map.put("money",totalPrice);
        map.put("type",112111);
        map.put("wallet_status",131101);
        map.put("remark","发布竞赛活动支出，竞赛活动编号为："+raceId);

        commonPayDao.addUser_wallet(map);
    }
    /**
     * 给中奖艺术家发奖金
     * @param list 中奖艺术家列表
     * @param xishu 奖金系数
     * @throws Exception
     */
    private void updateArtistWallet(List<Map<String, Object>> list,BigDecimal xishu,int raceId,int orderRaceId) throws Exception{
        for(Map<String, Object> map : list){
            //查出该中奖等级金额
            Map<String, Object> prize = commonPayDao.getPrizeByPrizeId(Integer.parseInt(map.get("prizeId").toString()));
            //根据竞赛活动查询
            if(prize == null){
                throw new Exception("不存在中奖等级");
            }
            //获得该等级中奖的艺术家
            String[] artistIds = map.get("artistIds").toString().split(",");
            BigDecimal prizeMoney = new BigDecimal(prize.get("money").toString()).multiply(xishu);
            for(String artistId : artistIds){
                Map<String, Object> map2 = new HashMap<String, Object>();
                Integer userId = commonPayDao.getUserInfoByArtistId(Integer.parseInt(artistId));
                //给艺术家钱包打钱并写入日志
                map2.put("prizeMoney",prizeMoney);
                map2.put("userId",userId);
                try{
                    commonPayDao.updateArtistWallet(map2);
                }catch (Exception e){
                    throw new Exception("给中奖艺术家打钱失败");
                }
                map2.put("user_id",userId);
                map2.put("money",prizeMoney);
                map2.put("type",112104);
                map2.put("wallet_status",131101);
                map2.put("remark","竞赛活动打款,竞赛活动编号为："+raceId);

                try{
                    commonPayDao.addUser_wallet(map2);
                }catch (Exception e){
                    throw new Exception("保存钱包日志失败");
                }
                //保存订单明细
                map2.put("orderRaceId",orderRaceId);
                map2.put("artistId",artistId);
                map2.put("prizeId",Integer.parseInt(map.get("prizeId").toString()));
                try{
                    raceOrderService.addOrderWin(map2);
                }catch (Exception e){
                    throw new Exception("保存订单明细失败");
                }
            }
        }
    }

    /**
     * 计算艺术家获奖金额系数
     * @param isFee 是否扣除手续费
     * @param isPopur 是否扣除推广费
     * @return
     * @throws Exception
     */
    private BigDecimal getXiShu(boolean isFee,boolean isPopur) throws Exception{
        BigDecimal xishu = new BigDecimal(1);
        if(isFee){//手续费系数
            BigDecimal fee = new BigDecimal(commonPayDao.findScaleValue(4));
            xishu = (xishu.multiply(fee)).divide(new BigDecimal(100));
        }
        if(isPopur){//推广费系数
            BigDecimal popur = new BigDecimal(commonPayDao.findScaleValue(5));
            xishu = (xishu.multiply(popur)).divide(new BigDecimal(100));
        }
        return new BigDecimal(1).subtract(xishu);
    }
}
